import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '../store/useAuthStore'
import { ElMessage } from 'element-plus'

// 定义路由
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: {
      title: '首页'
    }
  },
  {
    path: '/auth',
    name: 'Auth',
    redirect: '/auth/login',
    component: () => import('../views/layouts/AuthLayout.vue'),
    children: [
      {
        path: 'login',
        name: 'Login',
        component: () => import('../views/auth/Login.vue'),
        meta: {
          title: '登录',
          public: true
        }
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('../views/auth/Register.vue'),
        meta: {
          title: '注册',
          public: true
        }
      },
      {
        path: 'forgot-password',
        name: 'ForgotPassword',
        component: () => import('../views/auth/ForgotPassword.vue'),
        meta: {
          title: '忘记密码',
          public: true
        }
      },
      {
        path: 'reset-password',
        name: 'ResetPassword',
        component: () => import('../views/auth/ResetPassword.vue'),
        meta: {
          title: '重置密码',
          public: true
        }
      }
    ]
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue'),
    meta: {
      title: '关于我们'
    }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/User.vue'),
    meta: {
      title: '用户中心',
      requiresAuth: true
    }
  },
  {
    path: '/tools',
    name: 'Tools',
    component: () => import('../views/Tools.vue')
  },
  {
    path: '/history',
    name: 'History',
    component: () => import('../views/History.vue'),
    meta: {
      title: '处理历史',
      requiresAuth: true
    }
  },
  {
    path: '/user/profile',
    name: 'UserProfile',
    component: () => import('../views/user/Profile.vue'),
    meta: { title: '个人资料', requiresAuth: true }
  },
  {
    path: '/user/settings',
    name: 'UserSettings',
    component: () => import('../views/user/Settings.vue'),
    meta: { title: '账号设置', requiresAuth: true }
  },
  {
    path: '/user/security',
    name: 'UserSecurity',
    component: () => import('../views/user/Security.vue'),
    meta: { title: '密码修改', requiresAuth: true }
  },
  {
    path: '/account/settings',
    name: 'AccountSettings',
    component: () => import('../views/account/SettingsFixed.vue'),
    meta: { 
      title: '账号设置', 
      requiresAuth: true 
    }
  },
  {
    path: '/pricing',
    name: 'Pricing',
    component: () => import('../views/Pricing.vue')
  },
  {
    path: '/faq',
    name: 'FAQ',
    component: () => import('../views/FAQ.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
    meta: { title: '页面未找到' }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 设置标题
  document.title = `${to.meta.title ? to.meta.title + ' - ' : ''}水印去除工具`
  
  // 获取token和用户信息
  const token = localStorage.getItem('token')
  const userJson = localStorage.getItem('user')
  
  console.log('路由守卫检查:', {
    path: to.path,
    hasToken: !!token,
    hasUser: !!userJson,
    requiresAuth: to.meta.requiresAuth,
    isPublic: to.meta.public
  })
  
  // 检查是否需要登录权限
  const authStore = useAuthStore()
  
  // 如果有token和用户信息，但store中没有，则从localStorage加载
  if (token && userJson && !authStore.user) {
    console.log('从localStorage加载用户信息到store')
    authStore.loadUserFromStorage()
  }
  
  // 检查token是否过期
  if (token) {
    try {
      // 解码JWT token的payload部分
      const base64Url = token.split('.')[1]
      // 添加padding
      const padding = '='.repeat((4 - base64Url.length % 4) % 4)
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/') + padding
      
      // 直接使用atob解码base64
      const jsonPayload = atob(base64)
      const payload = JSON.parse(jsonPayload)
      
      // 检查token是否有效
      if (!payload.exp || !payload.iat) {
        console.warn('Token缺少必要的时间戳，但继续允许访问')
        next()
        return
      }
      
      // 检查token是否在有效期内
      const now = Math.floor(Date.now() / 1000) // 转换为秒级时间戳
      const issuedAt = payload.iat
      const expiresAt = payload.exp
      
      console.log('Token有效期检查:', {
        issuedAt: new Date(issuedAt * 1000).toLocaleString(),
        expiresAt: new Date(expiresAt * 1000).toLocaleString(),
        now: new Date(now * 1000).toLocaleString(),
        isValid: now >= issuedAt && now < expiresAt,
        timeDiff: expiresAt - now,
        payload
      })
      
      // 如果token已过期，清除登录状态
      if (now >= expiresAt) {
        // 检查是否接近过期（比如还有5分钟过期）
        const timeToExpire = expiresAt - now
        if (timeToExpire < 300) { // 5分钟 = 300秒
          console.warn('Token即将过期，尝试刷新')
          try {
            // 这里可以添加刷新token的逻辑
            // const newToken = await authStore.refreshToken()
            // if (newToken) {
            //   next()
            //   return
            // }
          } catch (error) {
            console.error('刷新Token失败:', error)
          }
        }
        
        console.warn('Token已过期，清除认证状态')
        // 清除localStorage
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        localStorage.removeItem('refresh_token')
        
        // 重置store
        authStore.$reset()
        
        if (to.meta.requiresAuth) {
          ElMessage.warning('登录已过期，请重新登录')
          next({ name: 'Login', query: { redirect: to.fullPath } })
          return
        }
      }

      // Token有效，只在必要时获取最新的用户信息
      if (to.meta.requiresAuth && !authStore.user) {
        try {
          const response = await authStore.getCurrentUser()
          if (!response) {
            throw new Error('获取用户信息失败')
          }
        } catch (error) {
          console.error('获取用户信息失败:', error)
          if (to.meta.requiresAuth) {
            ElMessage.error('获取用户信息失败，请重新登录')
            next({ name: 'Login', query: { redirect: to.fullPath } })
            return
          }
        }
      }
      
      next()
    } catch (e) {
      console.warn('Token解析失败，但继续允许访问:', e)
      // Token解析错误，但不立即清除，让后端API来判断token的有效性
      if (to.meta.requiresAuth && !authStore.user) {
        try {
          const response = await authStore.getCurrentUser()
          if (!response) {
            throw new Error('获取用户信息失败')
          }
        } catch (error) {
          console.error('获取用户信息失败:', error)
          if (to.meta.requiresAuth) {
            ElMessage.error('获取用户信息失败，请重新登录')
            next({ name: 'Login', query: { redirect: to.fullPath } })
            return
          }
        }
      }
      next()
    }
  } else if (to.meta.requiresAuth) {
    // 没有token但需要认证
    ElMessage.warning('请先登录')
    next({ name: 'Login', query: { redirect: to.fullPath } })
    return
  } else {
    next()
  }
})

export default router 